﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using BoardPACBO.Meeting;
using BoardPACDAO.Entity;
using System.Configuration;
using BoardAppUtil.Util;
using BoardPACBO.UserMgt;
using BoardPACBO.Paper;

namespace BoardPACDAO.Mappers
{
    public static class Mapper
    {
        #region Meeting Mappings

        #region Meetings

        /// <summary>Convert meeting model values to dictionary list values.</summary>
        ///<param name="entity">Job Entity</param>
        ///<param name="meeting"></param>
        ///<param name="user"></param>
        ///<returns>
        ///ListDictionary containing the tags and it's values
        ///</returns>      
        /// <remarks>
        /// This result of this method is used for generating the body string of the email.
        /// The template is placed at Views\Shared\Email Templates\MeetingEmailTemp.txt
        /// </remarks>         
        public static ListDictionary MeetingToDictionary(MeetingModel meeting, User user, String datePreposition, User BSUser)
        {
            //For Email only
            try
            {
                #region Old E-Mail code was commented

                ////List Dictionary must contain only string values
                //ListDictionary replacements = new ListDictionary();
                //replacements.Add("<%Subject%>",getStringValue(meeting.Subject));

                //if (meeting.Date!=null)
                //{
                //    //replacements.Add("<%Date%>", String.Format("{0:dd/MM/yyyy}",(DateTime) meeting.Date));
                //    replacements.Add("<%Date%>", Formatter.GetDateOnlyFormat(meeting.Date));
                //}
                //else
                //{
                //    replacements.Add("<%Date%>", string.Empty);
                //}

                //replacements.Add("<%FirstName%>",getStringValue(user.FirstName));
                //replacements.Add("<%SubCategoryName%>", getStringValue(meeting.SubCategoryName));                          
                //// NTB UAT Requirement changes
                ////replacements.Add("<%LastName%>", getStringValue(user.LastName));
                ////replacements.Add("<%Description%>", getStringValue(meeting.Description)); 

                //replacements.Add("<%MeetingType%>", getStringValue(meeting.meetingTypeName));  

                //return replacements;               

                #endregion

                //List Dictionary must contain only string values
                ListDictionary replacements = new ListDictionary();

                String Salutation = user.Title ?? String.Empty;

                replacements.Add("<%FirstName%>", getStringValue(user.FirstName));

                //2012-09-19 Updated for template
                replacements.Add("<%Salutation%>", Salutation);
                replacements.Add("<%LastName%>", " " + getStringValue(user.LastName));
                replacements.Add("<%SubCategory%>", getStringValue(meeting.SubCategoryName));
                replacements.Add("<%MeetingType%>", getStringValue(meeting.meetingTypeName));

                replacements.Add("<%Description%>", String.IsNullOrWhiteSpace(getStringValue(meeting.Description)) ? String.Empty : getStringValue(meeting.Description));
                replacements.Add("<%Venue%>", String.IsNullOrWhiteSpace(getStringValue(meeting.Venue)) ? String.Empty : "at " + getStringValue(meeting.Venue));
                replacements.Add("<%MeetingAt%>", String.IsNullOrWhiteSpace(getStringValue(meeting.Address)) ? String.Empty : "of " + getStringValue(meeting.Address));

                //2013-08-05 added to put the names of BoardSecretary
                replacements.Add("<%BSLastName%>", " " + getStringValue(BSUser.LastName));
                replacements.Add("<%BSFirstName%>", " " + getStringValue(BSUser.FirstName));
                replacements.Add("<%BSSalutation%>", getStringValue(BSUser.Title));

                if (!meeting.isTentative)
                {
                    replacements.Add("<%MeetingDate%>", datePreposition + "<b>" + getStringValue(((DateTime)meeting.Date).ToString(ConfigurationManager.AppSettings["dateOnlyFormat"].ToString())) + "</b>");
                }
                else
                {
                    replacements.Add("<%MeetingDate%>", ConfigurationManager.AppSettings["infoMeetingEmailTentative"].ToString());
                }

                replacements.Add("<%MeetingTime%>", ((!meeting.isTentative) && (meeting.meetingType != 1)) ? " at " + "<b>" + getStringValue(meeting.startTime) + "</b>" : String.Empty);
                               
                string bodyContent = string.Empty;
                /*if (meeting.meetingType == 0) //meeting
                {
                    bodyContent = Resources.info_emailBodyofMeeting + " " + getStringValue(meeting.Subject) + ".";
                }
                else //circular
                {
                    bodyContent = Resources.info_emailBodyofCircular;
                }*/

                if (meeting.meetingType == 0) //meeting
                {
                    //todo - calling resource from data access
                    bodyContent = "We have commenced uploading papers for the " + getStringValue(meeting.Subject) + ".";
                }
                else //circular
                {
                    //todo - calling resource from data access
                    bodyContent = "We have uploaded paper/s for your approval by circulation.";
                }
                replacements.Add("<%MsgContent%>", bodyContent);
                return replacements;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_220_sys");
            }
        }

        public static ListDictionary PaperAlertToDictionary(MeetingModel meeting, User user, String datePreposition, List<string> paperNames, User BSUser)
        {
            //For Email only
            try
            {
                //List Dictionary must contain only string values
                ListDictionary replacements = new ListDictionary();

                String Salutation = user.Title ?? String.Empty;  //"Mr. ";

                replacements.Add("<%FirstName%>", getStringValue(user.FirstName));

                //2012-09-19 Updated for template
                replacements.Add("<%Salutation%>", Salutation);
                replacements.Add("<%LastName%>", " " + getStringValue(user.LastName));
                replacements.Add("<%SubCategory%>", getStringValue(meeting.SubCategoryName));
                replacements.Add("<%MeetingType%>", getStringValue(meeting.meetingTypeName.Replace("(", string.Empty).Replace(")", string.Empty)));

                //replacements.Add("<%Description%>", String.IsNullOrWhiteSpace(getStringValue(meeting.Description)) ? String.Empty : getStringValue(meeting.Description));

                //2013-08-05 added to put the names of BoardSecretary
                replacements.Add("<%BSLastName%>", " " + getStringValue(BSUser.LastName));
                replacements.Add("<%BSFirstName%>", " " + getStringValue(BSUser.FirstName));
                replacements.Add("<%BSSalutation%>", getStringValue(BSUser.Title));

                if (!meeting.isTentative)
                {
                    replacements.Add("<%MeetingDate%>", datePreposition + "<b>" + getStringValue(((DateTime)meeting.Date).ToString(ConfigurationManager.AppSettings["dateOnlyFormat"].ToString())) + "</b>");
                }
                else
                {
                    replacements.Add("<%MeetingDate%>", ConfigurationManager.AppSettings["infoMeetingEmailTentative"].ToString());
                }

                replacements.Add("<%MeetingTime%>", ((!meeting.isTentative) && (meeting.meetingType != 1)) ? " at " + "<b>" + getStringValue(meeting.startTime) + "</b>" : String.Empty);

                string bodyContent = string.Empty;
                bodyContent = "<ul>";
                for (int i = 0; i < paperNames.Count; i++)
                {
                    //bodyContent = bodyContent + "<br> &nbsp;&nbsp;&nbsp;" + (i + 1) + ". " + paperNames[i];
                    bodyContent = bodyContent + "<li>" + paperNames[i] + "</li>";
                }
                bodyContent = bodyContent + "</ul>";
                replacements.Add("<%MsgContent%>", bodyContent);

                return replacements;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_220_sys");
            }
        }

        public static ListDictionary MeetingPresentDetailsToDictionary(AgendaDetail complatedPaper, AgendaDetail paper, MeetingModel meeting, string datePreposition)
        {
            try
            {
                ListDictionary replacements = new ListDictionary();

                replacements.Add("<%RecipiantName%>", getStringValue(paper.PresenterName));
                replacements.Add("<%RecipiantEmail%>", getStringValue(paper.PresenterEmail));

                replacements.Add("<%PresenterName%>", getStringValue(complatedPaper.PresenterName));
                replacements.Add("<%PresenterEmail%>", getStringValue(complatedPaper.PresenterEmail));
                replacements.Add("<%PaperStartTime%>", getStringValue(complatedPaper.StartTime));
                replacements.Add("<%PaperEndTime%>", getStringValue(complatedPaper.EndTime));
                replacements.Add("<%PaperName%>", getStringValue(complatedPaper.Paper.Name));

                replacements.Add("<%SubCategory%>", getStringValue(meeting.SubCategoryName));
                replacements.Add("<%MeetingType%>", getStringValue(meeting.meetingTypeName));
                replacements.Add("<%Description%>", String.IsNullOrWhiteSpace(getStringValue(meeting.Description)) ? String.Empty : getStringValue(meeting.Description));
                replacements.Add("<%Venue%>", String.IsNullOrWhiteSpace(getStringValue(meeting.Venue)) ? String.Empty : "at " + getStringValue(meeting.Venue));
                replacements.Add("<%MeetingAt%>", String.IsNullOrWhiteSpace(getStringValue(meeting.Address)) ? String.Empty : "of " + getStringValue(meeting.Address));

                if (!meeting.isTentative)
                {
                    replacements.Add("<%MeetingDate%>", datePreposition + getStringValue(((DateTime)meeting.Date).ToString(ConfigurationManager.AppSettings["dateOnlyFormat"].ToString())));
                }
                else
                {
                    replacements.Add("<%MeetingDate%>", ConfigurationManager.AppSettings["infoMeetingEmailTentative"].ToString());
                }

                replacements.Add("<%MeetingTime%>", ((!meeting.isTentative) && (meeting.meetingType != 1)) ? " at " + getStringValue(meeting.startTime) : String.Empty);

                return replacements;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_220_sys");
            }
        }

        public static ListDictionary MeetingPresentDetailsToDictionary(AgendaDetailModel complatedPaper, AgendaDetailModel paper, MeetingModel meeting, string datePreposition)
        {
            try
            {
                ListDictionary replacements = new ListDictionary();

                replacements.Add("<%RecipiantName%>", getStringValue(paper.PresenterName));
                replacements.Add("<%RecipiantEmail%>", getStringValue(paper.PresenterEmail));

                replacements.Add("<%PresenterName%>", getStringValue(complatedPaper.PresenterName));
                replacements.Add("<%PresenterEmail%>", getStringValue(complatedPaper.PresenterEmail));
                replacements.Add("<%PaperStartTime%>", getStringValue(complatedPaper.StartTime));
                replacements.Add("<%PaperEndTime%>", getStringValue(complatedPaper.EndTime));
                replacements.Add("<%PaperName%>", getStringValue(complatedPaper.PaperName));

                replacements.Add("<%SubCategory%>", getStringValue(meeting.SubCategoryName));
                replacements.Add("<%MeetingType%>", getStringValue(meeting.meetingTypeName));
                replacements.Add("<%Description%>", String.IsNullOrWhiteSpace(getStringValue(meeting.Description)) ? String.Empty : getStringValue(meeting.Description));
                replacements.Add("<%Venue%>", String.IsNullOrWhiteSpace(getStringValue(meeting.Venue)) ? String.Empty : "at " + getStringValue(meeting.Venue));
                replacements.Add("<%MeetingAt%>", String.IsNullOrWhiteSpace(getStringValue(meeting.Address)) ? String.Empty : "of " + getStringValue(meeting.Address));

                if (!meeting.isTentative)
                {
                    replacements.Add("<%MeetingDate%>", datePreposition + getStringValue(((DateTime)meeting.Date).ToString(ConfigurationManager.AppSettings["dateOnlyFormat"].ToString())));
                }
                else
                {
                    replacements.Add("<%MeetingDate%>", ConfigurationManager.AppSettings["infoMeetingEmailTentative"].ToString());
                }

                replacements.Add("<%MeetingTime%>", ((!meeting.isTentative) && (meeting.meetingType != 1)) ? " at " + getStringValue(meeting.startTime) : String.Empty);

                return replacements;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_220_sys");
            }
        }

        public static AgendaDetailModel AgendaDetailEntityToModel(AgendaDetail entity, bool isPaperIncludedInEagerLoading)
        {
            return new AgendaDetailModel()
            {
                PaperId = entity.PaperId,
                PresenterName = entity.PresenterName,
                PresenterEmail = entity.PresenterEmail,
                StartTime = entity.StartTime,
                EndTime = entity.EndTime,
                IsCompleted = entity.IsCompleted,
                PaperName = (isPaperIncludedInEagerLoading) ? entity.Paper.Name : string.Empty // Include("Paper") in entity linq query
            };
        }

        public static MeetingModel MeetingEntityToModel(Entity.Meeting meetingEntity)
        {
            try
            {
                MeetingModel meetingModel = new MeetingModel();
                meetingModel.MeetingId = meetingEntity.MeetingId;
                meetingModel.Date = meetingEntity.Date;
                meetingModel.Subject = meetingEntity.Subject;
                meetingModel.Description = meetingEntity.Description;
                meetingModel.SubCategoryId = meetingEntity.SubCategoryId;
                meetingModel.SubCategoryName = meetingEntity.SubCategory.Name;
                meetingModel.CategoryId = meetingEntity.SubCategory.CategoryId;
                meetingModel.MeetingStatus = meetingEntity.Status;
                meetingModel.previosStatus = meetingEntity.Status;
                meetingModel.isTentative = meetingEntity.IsTentative;
                meetingModel.startTime = meetingEntity.StartTime != null ? new DateTime(((TimeSpan)meetingEntity.StartTime).Ticks).ToString("T") : String.Empty;
                //  meetingModel.endTime =(meetingEntity.EndTime!=null)? meetingEntity.EndTime.ToString():null;
                meetingModel.endTime = meetingEntity.EndTime.ToString();
                meetingModel.meetingType = meetingEntity.MeetingType;
                meetingModel.Address = meetingEntity.Address;
                meetingModel.Venue = meetingEntity.Venue;


                return meetingModel;
            }
            catch (Exception)
            {
                // Error occurred in Mapper
                throw new GenServiceException("err_221_sys"); ;

            }
        }

        #endregion

        #region Meeting Template

        public static MeetingTemplateModel MeetingTemplateEntityToModel(MeetingTemplate meetingTemplate)
        {
            return new MeetingTemplateModel()
            {
                MeetingTemplateId = meetingTemplate.MeetingTemplateId,
                TemplateName = meetingTemplate.TemplateName,
                Address = meetingTemplate.Address,
                Venue = meetingTemplate.Venue,
                Longitude = meetingTemplate.Longitude,
                Latitude = meetingTemplate.Latitude
            };
        }

        public static MeetingTemplate MeetingTemplateModelToEntity(MeetingTemplateModel meetingTemplate)
        {
            return new MeetingTemplate()
            {
                MeetingTemplateId = meetingTemplate.MeetingTemplateId,
                TemplateName = meetingTemplate.TemplateName,
                Address = meetingTemplate.Address,
                Venue = meetingTemplate.Venue,
                Longitude = meetingTemplate.Longitude,
                Latitude = meetingTemplate.Latitude,
            };
        }


        public static PaperModel PaperEntityToModel(Entity.Paper entity)
        {
            return new PaperModel()
            {
                AdditionalRefId = entity.AdditionalRefId,
                //ApprovalsModelList = entity.
                //CategoryID = entity.
                //CommentModelList = entity.
                CreatedBy = entity.CreatedBy,
                CreatedDate = entity.CreatedDate,
                Description = entity.Description,
                DocName = entity.Name,
                DocType = entity.DocType,
                //DocTypeValue = entity.
                //FilePath = entity.
                headingId = entity.HeadingId,
                IsPwdProtected = entity.IsPwdProtected,
                Keywords = entity.Keyword,
                //meetingId = entity.
                NewPaperStatus = entity.PaperStatus,
                Order = entity.AgendaOrder,
                paperColor = entity.PaperColor,
                PaperId = entity.PaperId,
                PaperRefNo = entity.PaperRefNo,
                //PreviousPaperStatusValue = entity.
                //ScrollDirection = entity.
                StatusComment = entity.StatusComment
            };
        }


        public static List<PaperModel> PaperEntityListToModelList(List<Entity.Paper> entities)
        {
            List<PaperModel> papers = new List<PaperModel>();
            try
            {
                entities.ForEach(x => papers.Add(Mapper.PaperEntityToModel(x)));
            }
            catch (Exception)
            {
                //todo:log on exception
            }
            return papers;
        }

        #endregion

        #endregion Meetings

        #region ResetPassword

        public static ListDictionary ResetPWToDictionary(UserMgtModelsMetadata user, String NewPassword)
        {
            //For Email only
            try
            {
                String Salutation = user.saluation ?? String.Empty; //"Mr. ";
                String AdditionalMsg = String.Empty;

                ListDictionary replacements = new ListDictionary();
                replacements.Add("<%FirstName%>", user.firstName.ToString());
                replacements.Add("<%LastName%>", " " + user.lastname.ToString());
                replacements.Add("<%UserName%>", " " + user.username.ToString());
                replacements.Add("<%AdditionalMsg%>", AdditionalMsg);
                replacements.Add("<%Salutation%>", Salutation);
                replacements.Add("<%Password%>", NewPassword);
                return replacements;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_220_sys");
            }
        }
        #endregion ResetPassword

        #region AddUser

        public static ListDictionary AddUserToDictionary(User user, String NewPassword)
        {
            //For Email only
            try
            {
                String Salutation = user.Title ?? String.Empty;
                String AdditionalMsg = String.Empty;

                ListDictionary replacements = new ListDictionary();
                replacements.Add("<%FirstName%>", user.FirstName.ToString());
                replacements.Add("<%LastName%>", " " + user.LastName.ToString());
                replacements.Add("<%UserName%>", " " + user.UserName.ToString());
                replacements.Add("<%AdditionalMsg%>", AdditionalMsg);
                replacements.Add("<%Salutation%>", Salutation);
                replacements.Add("<%Password%>", NewPassword);
                return replacements;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_220_sys");
            }
        }


        public static ListDictionary AddUserToDictionary(UserMgtModelsMetadata user, String NewPassword)
        {
            //For Email only
            try
            {
                String Salutation = user.saluation ?? String.Empty;
                String AdditionalMsg = String.Empty;

                ListDictionary replacements = new ListDictionary();
                replacements.Add("<%FirstName%>", user.firstName.ToString());
                replacements.Add("<%LastName%>", " " + user.lastname.ToString());
                replacements.Add("<%UserName%>", " " + user.username.ToString());
                replacements.Add("<%AdditionalMsg%>", AdditionalMsg);
                replacements.Add("<%Salutation%>", Salutation);
                replacements.Add("<%Password%>", NewPassword);
                return replacements;
            }
            catch (Exception)
            {
                throw new GenServiceException("err_220_sys");
            }
        }

        #endregion AddUser

        #region Private Methods

        /// <summary>get string value of any job field. This is used by ModelToDictionaryValues() for email purposes.</summary>
        /// <param name="jobfield"> any job field</param>
        ///<returns>
        ///string value of any field.
        ///</returns>      
        /// <remarks>
        /// This is the inverse of getInnerTextMethod
        /// </remarks> 
        private static string getStringValue(object value)
        {
            if (value == null)
            {
                return string.Empty;
            }
            else
            {
                return value.ToString();
            }
        }

        #endregion PrivateMethods



        public static List<UserMgtModelsMetadata> UserEntityToUserMgtModelsMetadata(List<User> recips)
        {
            try
            {
                List<UserMgtModelsMetadata> userModel = new List<UserMgtModelsMetadata>();
                foreach (var item in recips)
                {
                    userModel.Add(
                        new UserMgtModelsMetadata()
                            {
                                customUserId = item.CustomUserId,
                                displayName = item.DisplayName,
                                email = item.BoardEmail,
                                firstName = item.FirstName,
                                //imagePath = item.
                                //isLocked = item.
                                lastname = item.LastName,
                                mobileno = item.MobileNumber,
                                //modifiedBy = (int)item.ModifiedBy,
                                officeEmail = item.OfficeEmail,
                                officeno = item.OfficePhone,
                                passwordReseted = item.PasswordReseted,
                                //roleName = item.
                                //saluation = item.
                                username = item.UserName,
                                userStatus = item.Status,
                            }
                        );
                }
                return userModel;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
